<?php


namespace App\Exports;

use App\Models\RecordOrder;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
/**
 * Created By FreeAbrams
 * Date: 2020/12/1
 */
class OrderExport implements FromView
{
	protected $timeBetween;
	protected $sum = 0;
	protected $status = [1 => '未支付', 2 => '待消费', 3 => '使用中', 4 => '已完成', 5 => '已取消'];
	
	public function __construct($timeBetween)
	{
		$this->timeBetween = $timeBetween;
	}
	
	public function view():View
	{
		$temp = $this->data($this->timeBetween);
		
		//foreach ($temp as $v){
		//	dd($v[11]->count());
		//}
		return view('admin.export.order-export-table', ['data' => $temp,
			'sum' => $this->sum,
			'status' => $this->status
		]);
	}
	
	protected function data($timeBetween)
	{
		$store_id = Admin::user()->store_id;
		$orders = RecordOrder::with(['order' => function($q){
			$q->withTrashed()->selectRaw('id, status');
		}])->whereBetween('created_at', $timeBetween)
			->where('store_id', $store_id)
			->get(['id', 'store_id', 'order_id', 'price', 'created_at']);

		// 增加分组列
		$orders = $orders->map(function ($item) {
			$date = New Carbon($item->created_at);
			$item->date = $date->format('m');
			return $item;
		});
		// 名称分组后date分组
		$orders = $orders->groupBy('order.status')->map(function ($item) {
			return $item->groupBy('date');
		});
		$orders = $orders->map(function ($item) {
			for ($i = 0; $i < 12; $i++){
				isset($item[$i+1])?$item[$i+1]:$item[$i+1] = collect([]);
			}
			return $item;
		});
		//dd($orders);
		return $orders;
	}
}